// $Id: user_map.js 271 2008-09-26 18:00:07Z hugo.wetterberg $

/*extern $, google, Drupal, GMarker */

/**
 * @fileOverview Controlls the User Map Functionality
 * @name UserMap
 */

if (google && google.load) {
  var UserMap = function (rect) {
    var placeholder, info_window, map,
      wkt_to_latlng = function (wkt) {
        var coords = wkt.split(' ');
        if (coords.length >= 2) {
          return new google.maps.LatLng(coords[0], coords[1]);
        }
      },
      obj = {}, 
      markers = [];
    
    obj.setCenter = function (point) {
      if (map) {
        map.setCenter(wkt_to_latlng(point));
      }
    };
    
    var get_bounds = function() {
      var bounds = new GLatLngBounds();
      var points = rect.split(',');
      var pc = points.length;
      for(var i=0; i<pc; i++) {
        var p = points[i].split(' ');
        bounds.extend(new GLatLng(p[0],p[1]));
      }
      return bounds;
    };
    
    var show_markers = function (res, err) { 
      if (!res) {
        return;
      }
      
      var res_count, position, marker, i, icons={};
      var icon = function(item) {
        if (!icons[item[3]]) {
          var icon = new GIcon(G_DEFAULT_ICON);
          icon.shadow = null;
          icon.iconSize = new GSize(20, 29);
          icon.iconAnchor = new GPoint(9, 29);
          icon.image = Drupal.settings.user_map.favicon_path +'/'+ item[3] +'/marker.png';
          return icons[item[3]] = icon;
        }
        return icons[item[3]];
      },
      marker_setup = function(item, marker, position) {
        marker.feed = item[4];
        markers.push(marker);
        GEvent.addListener(marker, "click", function() {
          var pos = map.fromLatLngToContainerPixel(position);
          info_window.html('<b><a href="'+ Drupal.settings.basePath +'js-node-link/'+ item[0] +'">' + item[1] + "</a></b><br/>").css({
            'top': pos.y,
            'left': pos.x
          }).show();
        });
      };
      
      res_count = res['items'].length;
      for (i = 0; i < res_count; i++) {
        position = wkt_to_latlng(res['items'][i][2]);
        marker = new google.maps.Marker(position, {'icon':icon(res['items'][i])});
        marker_setup(res['items'][i], marker, position);        
        map.addOverlay(marker);
      }
    };
    
    var toggle_markers = function(feed, hide)
    {
      for(var marker, i = 0; i < markers.length; i++)
      {
        marker = markers[i];
        if(marker.feed == feed)
        {
          if(hide)
          {
            marker.hide();
          }
          else
          {
            marker.show();
          }
        }
      }
    };
    
    var show_favorites = function(subs) {
      if (subs) {
        var feeds = {};
        for (var k in subs) {
          feeds[k] = subs[k][2];
        }
        $('#user-map-favorites-content .feeds').go_paginator({
          subscriptions: subs, 
          hiddenFeeds: {},
          pageSize: 9,
          maxCacheTime: 0, 
          initialized: false,
          filter: '', 
          onGotoPage: function(evt, pageNr)
          {
            var settings = $.data($(this).get(0), 'settings'), feed, i = 0;
            if(!settings.initialized)
            {
              for(feed in settings.subscriptions)
              {
                if(settings.filter.length && settings.subscriptions[feed][0].toLowerCase().indexOf(settings.filter) == -1)
                {
                  continue;
                }
                i++;
              }
              settings.pageCount = (i ? Math.ceil(i/settings.pageSize) : 1);
              $(settings.container).triggerHandler('num_pages_changed');
              $(this).show();
              settings.mapInitialized = true;
            }
            if(pageNr < 0)
            {
              pageNr = settings.pageCount-1;
            }
            else if(settings.pageCount <= pageNr)
            {
              pageNr = 0;
            }
            
            settings.gotoPage = pageNr;
            
            var offset = pageNr * settings.pageSize,
            data = {page: pageNr, pageCount: settings.pageCount, items: []};
            i = 0;
            for(feed in settings.subscriptions)
            {
              i++;
              if(settings.filter.length && settings.subscriptions[feed][0].toLowerCase().indexOf(settings.filter) == -1)
              {
                continue;
              }
              if(i > offset)
              {
                data.items.push({feed: feed, title: settings.subscriptions[feed][0]});
              }
              if(data.items.length >= settings.pageSize)
              {
                break;
              }
            }
            
            return $(this).triggerHandler('render_page', [data]);
          },
          onConstructListItems: function(evt, data)
          {
            var settings = $.data($(this).get(0), 'settings');
            var items = data.items, 
              list = $(this).find('.listing.animation');
            
            for(var el, item, j, i = list.find('li').length; i < items.length; i++)
            {
              item = list.append($('<li></li>').append($('<a class="title"></a>').click(function(){
                var el = $(this).parent('li').toggleClass('selected'),
                    feed = $.data($(el).get(0), 'feed'), 
                    visible = el.hasClass('selected');
                settings.hiddenFeeds[feed] = !visible;
                if(visible)
                {
                 toggle_markers(feed, false);
                }
                else
                {
                 toggle_markers(feed, true);
                }
              })).append($('<a class="remove"></a>').click(function(){
                $(this).parent('li').remove();
              })));
            }
            list.find('li:lt(' + (items.length) + ')').show();
            list.find('li:gt(' + (items.length - 1) + ')').hide();
            
            for(i = 0; i < items.length; i++)
            {
              item = items[i];
              el = list.find('li:eq(' + i + ')');
              el.find('.title').text(item.title).prepend('<img class="node-type" width="20" height="20" src="' + Drupal.settings.user_map.favicon_path +'/feed/'+ item.feed +'/icon/light.png" />');

              $.data(el.get(0), 'feed', item.feed);
              if(settings.hiddenFeeds[item.feed])
              {
                el.removeClass('selected');
              }
              else
              {
                el.addClass('selected');
              }
            }
            list.find('li:first').addClass('first');
            list.find('li:eq(' + (items.length - 1) + ')').addClass('last');
          }
        }).bind('set_filter', function(evt, filter){
          var settings = $.data($(this).get(0), 'settings');
          settings.filter = filter;
          settings.initialized = false;
          $(this).triggerHandler('goto_page', [0]);
        });
        
        
        Drupal.service('user_channels.feed_map_items', 
          [
            feeds, //Feeds to look in
            {}, //Filters to apply
            ['nid', 'title'] //Attributes to get
          ], 
          show_markers
        );
      }
    };
    
    google.load('maps', '2.x');
  
    $(function () {
      placeholder = $('#user-map-widget').get(0);
      if (placeholder) {
        // Drupal.service('user_channels.add_favorite', ['city_group/group_news/27','Mitt postnummer',[],3],function(){});
        // Drupal.service('user_channels.add_favorite', ['city_group/group_news/33','Tivoli',[],3],function(){});
        map = new google.maps.Map2(placeholder);
        map.addControl(new GSmallMapControl());
        GEvent.addListener(map, "movestart", function(){
          info_window.hide();
        });
        
        var bounds = get_bounds();
        var default_zoom = map.getBoundsZoomLevel(bounds);
        var default_center = bounds.getCenter();
        map.setCenter(default_center, default_zoom);
        
        $('#user-map-widget-wrapper').prepend('<div id="user-map-info-window"></div>');
        info_window = $('#user-map-info-window');
        show_favorites(Drupal.user_channels.subscriptions(1));
        var emptyOnFocus = function()
          {
            $(this).val('');
            $(this).unbind('focus', emptyOnFocus);
          };
        $('#filter-favorites').focus(emptyOnFocus).keyup(function(evt)
        {
          if(evt.which == 27 /* escape */)
          {
            $(this).val('');
          }
          $('#user-map-favorites-content .feeds').triggerHandler('set_filter', [$(this).val().toLowerCase()]);
        });
      }
    });  
    
    return obj;
  };
}

jQuery('#user-map-favorites .toggle-favorites').click(function() {
  var el = jQuery('#user-map-favorites-content').toggle();
  jQuery('#user-map-favorites-content .listing-wrapper').height(jQuery('#user-map-favorites-content .listing.current').height());
  jQuery(this).find('*').text(el.css('display') == 'none' ? Drupal.t('Show') : Drupal.t('Hide'));
});

$(document).ready(function(){
  UserMap(Drupal.settings.simple_geo_area);
});